import type { RoleListResult } from "@/api/types";
import type { UseBaseTable } from "@/composables";
import { ElMessage } from "element-plus";
import { reactive } from "vue";
import { roleApi } from "@/api";
import { useBaseTable } from "@/composables";
import { $t } from "@/plugins/i18n";
import { apiCall } from "@/utils/http/apiCall";

/** 角色查询表单 */
export interface RoleQuery {
    /** 角色名称 */
    name: string | null;
    /** 角色编码 */
    code: string | null;
}

interface UseRoleTable extends UseBaseTable<RoleListResult> {
    tableQuery: RoleQuery;
    fetchTableData: () => void;
    handleTableQuery: () => void;
    resetTableQuery: () => void;
    handleRecordDelete: (id: string) => void;
}

/** 角色表格 */
export function useRoleTable(): UseRoleTable {
    const { tableLoading, tableData, tablePage } = useBaseTable<RoleListResult>();

    const tableQuery = reactive<RoleQuery>({
        name: null,
        code: null,
    });

    /** 获取角色列表 */
    function fetchTableData(): void {
        tableLoading.value = true;
        const payload = {
            pageNum: tablePage.value.pageNum,
            pageSize: tablePage.value.pageSize,
            name: tableQuery.name,
            code: tableQuery.code,
        };

        apiCall(
            () => roleApi.page(payload),
            (data, resp) => {
                tableData.value = data || [];
                if ("page" in resp) {
                    tablePage.value.total = resp.page.total;
                }
            },
            {
                onFinally: () => {
                    tableLoading.value = false;
                },
            },
        );
    }

    /** 查询 */
    function handleTableQuery(): void {
        tablePage.value.pageNum = 1;
        fetchTableData();
    }

    /** 重置查询 */
    function resetTableQuery(): void {
        tableQuery.name = "";
        tableQuery.code = "";
        handleTableQuery();
    }

    /** 删除 */
    function handleRecordDelete(id: string): void {
        apiCall(
            () => roleApi.remove(id),
            (data, resp) => {
                ElMessage.success($t(resp.message));
                fetchTableData();
            },
        );
    }

    return {
        tableLoading,
        tableData,
        tablePage,
        tableQuery,
        fetchTableData,
        handleTableQuery,
        resetTableQuery,
        handleRecordDelete,
    };
}
